package com.group.service.impl;

import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.group.constants.UserConstants;
import com.group.entity.CommonResult;
import com.group.entity.user.UserAccountEntity;
import com.group.exception.IndustryException;
import com.group.mapper.UserAccountMapper;
import com.group.service.UserAccountService;
import com.group.utils.JWTUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;


@Service
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccountEntity> implements UserAccountService {

    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private RedisTemplate redisTemplate;
    @Override
    public CommonResult<?> userLogin(UserAccountEntity userAccountEntity)  {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userAccountEntity.getUserAccount(),userAccountEntity.getUserPassword());
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        if (authenticate!=null){
            CommonResult commonResult = new CommonResult();
            commonResult.setMsg("登录成功");
            String token = JWTUtils.getToken(userAccountEntity);
            commonResult.setData(token);
            redisTemplate.boundValueOps(UserConstants.USER_LOGIN_TOKEN+userAccountEntity.getUserAccount()).set(authenticate.getPrincipal());
            commonResult.setCode(200);
            return commonResult;
        }
        throw new IndustryException("账号名或者密码错误");
    }
}
